// const baseUrl = "http://47.102.222.71:8800"; //测试环境
// const baseUrl = "http://47.100.119.126:8800"; //测试环境
export const baseUrl = "http://test.cold360.cn"; //测试环境
// const baseUrl = "https://v2.cold360.cn/cloud360-web";//线上环境
import useUserStore from '@/store/user.js';
import {
	tansParams
} from '@/utils/tools.js'
const whiteList = ["/user/na_login"];
const formList = ["/cloud360-web/waring/list", "/cloud360-web/data/getDataByTUOKs",
	"/cloud360-cordata/dev/data/getDevData", "/cloud360-web/dev/data"
];
const apiList = ["/cloud360-cordata"];
const hideLoadingList = ["/cloud360-web/monitor/getMTData"];
const request = (options = {}) => {
	return new Promise((resolve, reject) => {
		if (hideLoadingList.indexOf(options.url) === -1) {
			uni.showLoading({
				title: "加载中"
			});
		}
		const token = useUserStore().token || uni.getStorageSync('token');
		if (!token && whiteList.indexOf(options.url) === -1) {
			// token不存在，跳转登录
			uni.redirectTo({
				url: "/pages/login/index"
			});
			uni.hideLoading()
			return;
		}
		let url = baseUrl + options.url + '?' + tansParams(options.data || options.params || {});
		if (!options.url.startsWith("/cloud360")) {
			//默认  /cloud360-web
			url = baseUrl + "/cloud360-web" + options.url + '?' + tansParams(options.data || options
				.params || {});
		}
		let contentType = "application/json";
		let data = {};
		if (formList.indexOf(options.url) !== -1 || options.isForm) {
			// FormData传参
			url = baseUrl + options.url;
			contentType = "application/x-www-form-urlencoded";
			data = options.data || options.params || {};
		} else {
			url = url.slice(0, -1);
		}
		url = encodeURI(url);
		uni.request({
			url: url,
			method: options.method,
			data: data,
			header: {
				'Content-Type': contentType, // 默认Content-Type
				'Authorization': token, // token
			},
			success: (res) => {
				if (res.statusCode == 401) {
					uni.showToast({
						icon: 'error',
						title: '请尝试重新登录！'
					});
					uni.redirectTo({
						url: "/pages/login/index"
					});
					return
				}
				//部分接口没有code
				res.data.code = res.data.code == undefined ? res.statusCode : res.data.code;
				if (res.data && res.data.code == 200) {
					return resolve(res.data)
				} else if (res.data && res.data.code == 401) {
					// 未登录、token失效
					uni.showToast({
						icon: 'error',
						title: '用户信息无效，请重新登录！'
					});
					uni.redirectTo({
						url: "/pages/login/index"
					});
					return
				} else if (res.data && res.data.code == 407) {
					// 账号未绑定
					return resolve(res.data)
				} else {
					uni.showToast({
						icon: 'none',
						title: res.data.msg || "系统未知错误，请反馈给管理员"
					});
				}
			},
			fail: (err) => {
				// 统一处理网络错误
				reject(err);
			},
			complete() {
				if (!options.noAutoHide) {
					uni.hideLoading();
				}
			}
		});
	});
};
export default request;